﻿using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace SmarterCharger.Library.Tests.Unit.Infrastructure
{
    public class TestBaseAsync<T>
    {
        protected ManualResetEvent EventTrigger { get; set; }
        protected T Result { get; set; }
        protected AggregateException Exception { get; set; }

        protected Exception BaseException {
            get
            {
                if (Exception == null) return null;

                return Exception.GetBaseException();
            }
        }

        [TestInitialize]
        public void Initialize()
        {
            try
            {
                Arrange();

                EventTrigger = new ManualResetEvent(false);

                Act().ContinueWith(r => 
                    {
                        if (r.Exception != null)
                            Exception = r.Exception;
                        else
                            Result = r.Result;

                        EventTrigger.Set();
                    });

                EventTrigger.WaitOne();
            }
            catch (Exception)
            {
                Cleanup();
                throw;
            }
        }

        [TestCleanup]
        public void Complete()
        {
            Cleanup();
        }

        protected virtual void Arrange()
        {
        }

        protected virtual Task<T> Act()
        {
            throw new NotImplementedException();
        }

        protected virtual void Cleanup()
        {
        }
    }
}
